import { Module } from 'vuex';
import type { ILoginState } from './type';
import type { IRootState } from '../type';

import cacheUtils from '@/utils/local';
import router from '@/router';

import { menuToRoute } from '@/utils/map-route';

import {
  accountLoginRequest,
  requestUserInfoById,
  getUserMenuByRoleId,
} from '@/service/login';

const login: Module<ILoginState, IRootState> = {
  namespaced: true, //开启命名空间 建议开启
  state() {
    return {
      token: '',
      userInfo: {},
      menus: [],
    };
  },
  mutations: {
    changeToken(state, token) {
      state.token = token;
    },
    changeUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    changeUserMenus(state, menus) {
      state.menus = menus;

      const realMenu = menuToRoute(menus);

      for (const menu of realMenu) {
        // 记得需要给main路由对象添加 name: 'main' 属性
        router.addRoute('main', menu);
      }
    },
  },
  actions: {
    async accountLoginAction({ commit }, info: any) {
      // console.log('触发accountLogin', info);

      // 缓存token
      const loginResult = await accountLoginRequest(info);
      const { id, token } = loginResult.data;
      commit('changeToken', token);
      cacheUtils.setCache('token', token);

      // 缓存用户个人信息
      const userInfoResult = await requestUserInfoById(id);
      commit('changeUserInfo', userInfoResult.data);
      // console.log(userInfoResult);
      cacheUtils.setCache('userInfo', userInfoResult.data);

      // 获取侧边栏信息
      const userMenu = await getUserMenuByRoleId(id);
      // console.log('accountLoginAction', userMenu);
      commit('changeUserMenus', userMenu.data);
      cacheUtils.setCache('userMenu', userMenu.data);

      // 页面跳转
      router.push('/main');
    },
    initLocalLogin({ commit }) {
      const token = cacheUtils.getCache('token');
      !!token && commit('changeToken', token);

      const userInfo = cacheUtils.getCache('userInfo');
      !!userInfo && commit('changeUserInfo', userInfo);

      const userMenu = cacheUtils.getCache('userMenu');
      !!userMenu && commit('changeUserMenus', userMenu);
    },
  },
};

export default login;
